package com.yuanfeng.payment.service.impl;


import com.yuanfeng.commoms.dto.base.MemberMessageListIntegralDTO;
import com.yuanfeng.commoms.dto.oos.OssUploadUpdateParamDTO;
import com.yuanfeng.commoms.dto.userms.UserPointLogDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.payment.feign.ActivityServiceClient;
import com.yuanfeng.payment.feign.OrderServiceClient;
import com.yuanfeng.payment.feign.ThirdPartyServiceClient;
import com.yuanfeng.payment.feign.UsermsServiceClient;
import com.yuanfeng.payment.mapper.PayConsumeRecordMapper;
import com.yuanfeng.payment.service.PaymentBalanceService;
import com.yuanfeng.payment.vo.QueryGoodsVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class PaymentBalanceServiceImpl implements PaymentBalanceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PaymentBalanceServiceImpl.class);
    @Autowired
    private PayConsumeRecordMapper recordMapper;

    @Autowired
    private UsermsServiceClient usermsServiceClient;

    @Autowired
    private OrderServiceClient orderServiceClient;

    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;

    @Autowired
    private ActivityServiceClient activityServiceClient;

    @Override
    public ResponseResult checkPaymentVocher(Map<Object, Object> map) {
        Map<String,String> orderIdIsNum = new HashMap<>();
        //虚拟订单 0 是 1 否
        Integer virtualGoods =null;
        //门店字体订单
        Integer orderIsShopTake = null;
        // 获取支付订单编号，并改变状态
        // 接收付款订单编号
        String orderId = (String) map.get("orderIdList");
        Map<String,Object> userMap = recordMapper.queryBuyUserId(orderId);
        String userId = userMap.get("buyerUserId").toString();
        orderIdIsNum.put("orderId",orderId);
        BigDecimal amountActuallyPaids = new BigDecimal(0);
        Integer amountAotalIntegral = null;
        //积分商品 0  是  1 否
        Integer integralGoods = 1;
        // 判断纯数字订单
        if (PayToolUtil.isInteger(orderId)) {
            QueryGoodsVO queryGoodsPara = recordMapper.queryGoodsPriceAndName(orderId, userId);
            BigDecimal paymentAmount = queryGoodsPara.getTradePaymentAmount();
            //获取积分商品订单的积分
            Integer totalIntegral = queryGoodsPara.getTotalIntegral();
            //积分商品 0  是  1 否
            integralGoods = queryGoodsPara.getIntegralGoods();
            amountAotalIntegral = totalIntegral;
            amountActuallyPaids = paymentAmount;
            //订单号是数字
            orderIdIsNum.put("isNum","0");
        }
        if(null != integralGoods && integralGoods == 0){
            //获取用户积分
            Integer userIntegral = usermsServiceClient.getMemberIntegralByUserId(userId);
            if(null != userIntegral && amountAotalIntegral <= userIntegral){
                //扣除积分
                //修改会员积分和会员等级
                MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                ArrayList<String> list = new ArrayList<>();
                list.add(userId);
                updateMemberMessageListIntegral.setUserIdList(list);
                updateMemberMessageListIntegral.setIntegral(amountAotalIntegral);
                //1是增加积分 0 是扣除积分
                updateMemberMessageListIntegral.setType(0);
                usermsServiceClient.updateMemberIntegral(updateMemberMessageListIntegral);
                //添加积分修改记录
                UserPointLogDTO userPointLog = new UserPointLogDTO();
                userPointLog.setPointsLogType(2);
                userPointLog.setClassId(7);
                userPointLog.setPointsLogTime(new Date());
                userPointLog.setPointsLogDesc("积分兑换商品");
                userPointLog.setPointsLogFlag("reg");
                userPointLog.setUserId(userId);
                userPointLog.setPointsLogPoints(amountAotalIntegral);
                userPointLog.setPointsLogOperate("积分兑换商品");
                userPointLog.setOrderId(orderId);
                usermsServiceClient.feginAddpointsLog(userPointLog);
            }else{
                //用户积分不足
                return ResponseResult.fail(BizCodeEnume.PAY_INTEGRAL_ERROR);
            }
        }
        //判断是否是虚拟订单
        Map<String, Integer> judgeOrderMap = this.virtualWxExchangeCode(orderIdIsNum);
        virtualGoods = judgeOrderMap.get("virtualGoods");
        orderIsShopTake = judgeOrderMap.get("orderIsShopTake");
        // 调用方法,更改状态
        // 存放值
        Map<Object, Object> statusMap = new HashMap<Object, Object>();
        // 是纯数字订单号，存放纯数字订单
        statusMap.put("orderId", orderId);
        statusMap.put("userId", userId);
        statusMap.put("userName", userMap.get("buyerUserName").toString());
        statusMap.put("type", 12);
        statusMap.put("paymentAmount", amountActuallyPaids);
        statusMap.put("amountAotalIntegral",amountAotalIntegral);
        //虚拟订单 0 是 1 否
        if(null != virtualGoods &&  0 == virtualGoods ){
            statusMap.put("virtualGoods",virtualGoods);
        }
        //虚拟订单 0 是 1 否
        if(null != orderIsShopTake &&  1 == orderIsShopTake ){
            statusMap.put("orderIsShopTake",orderIsShopTake);
        }
        changeStatus(statusMap);
        return ResponseResult.success();
    }

    /**
     * 更改状态
     *
     * @param map
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeStatus(Map<Object, Object> map) {
        String orderId = (String) map.get("orderId");
        Integer type = (Integer) map.get("type");
        Integer virtualGoods = (Integer) map.get("virtualGoods");
        Integer orderIsShopTake = (Integer) map.get("orderIsShopTake");
        Integer amountAotalIntegral = (Integer) map.get("amountAotalIntegral");
        String paymentTime = DateUtils.getTime();// 支付时间
        BigDecimal money = (BigDecimal) map.get("afterUserMoney");
        if (null == money) {
            money = new BigDecimal(0);
        }
        String userId = null;
        String userName = null;
        if(null == map.get("token")){
            userId = map.get("userId").toString();
            userName = map.get("userName").toString();
        }else{
            UserInfoVO ui = ParseTokenUtils.getUserInfoByToken((String) map.get("token"));
            userId = ui.getUserId();
            userName = ui.getUserName();
        }

        try {
            // 发送feign,提交下单通知
            Map<String, Object> messageMap = new HashMap<String, Object>();
            messageMap.put("userId", userId);
            messageMap.put("userName", userName);
            // 支付号
            messageMap.put("orderId", orderId);
            messageMap.put("paymentTime", paymentTime);
            // 发送下单通知
            ResponseResult responseResult = orderServiceClient.orderToInform(messageMap);
            if (responseResult.getCode() == 1) {
                LOGGER.info("-----OrderToInformUpdateSuccess-----");
            } else {
                LOGGER.info("-----OrderToInformUpdateFail-----");
            }

            // 更新trade&record状态
            LOGGER.info("StartUpdateTrade&RecordStatusTheFirstTime:" + DateUtils.getTime());
            boolean isUpdateRecordSuccess = false;
            boolean isUpdateRecordBySellerSuccess = false;
            Map<String, Object> mapRecord = new HashMap<>();
            mapRecord.put("orderId", orderId);
            mapRecord.put("money", money);
            mapRecord.put("userId", userId);
            mapRecord.put("paymentTime", paymentTime);
            mapRecord.put("amountAotalIntegral", amountAotalIntegral);
            if (PayToolUtil.isInteger(orderId)) {
                // 纯数字订单号
                // 用户，付款方
                isUpdateRecordSuccess = recordMapper.updateRecordByInt(mapRecord);
                // 商家，收款方
                isUpdateRecordBySellerSuccess = recordMapper.updateRecordBySellerInt(orderId, paymentTime);
                //获取非数字订单
                String record_payorder = orderServiceClient.queryUpayByOrderId(orderId);
                //修改拼团的支付状态
                Map<String,Object> pinTuanMap = new HashMap<>();
                pinTuanMap.put("orderId",record_payorder);
                activityServiceClient.updatePinTuanPayStart(pinTuanMap);
            } else {
                // 非纯数字订单号
                // 用户，付款方
                isUpdateRecordSuccess = recordMapper.updateRecord(mapRecord);
                // 商家，收款方
                isUpdateRecordBySellerSuccess = recordMapper.updateRecordBySeller(orderId, paymentTime);
                //修改拼团状态
                //修改拼团的支付状态
                Map<String,Object> pinTuanMap = new HashMap<>();
                pinTuanMap.put("orderId",orderId);
                activityServiceClient.updatePinTuanPayStart(pinTuanMap);
            }
            if (isUpdateRecordSuccess && isUpdateRecordBySellerSuccess) {
                LOGGER.info("-----UpdateTrade&RecordStatusSuccess-----");
                // 发送feign请求，更改payment状态
                Map<String, Object> paymentMap = new HashMap<String, Object>();
                // 支付方式
                Integer paymentId = 1;
                // 支付方式名称
                String paymentName = "在线支付";
                if (type==12) {
                    paymentId = 2;
                    paymentName = "线下支付";
                }
                // 分辨余额,购物卡,蜂币
                paymentMap.put("type", type);
                paymentMap.put("payOrderId", orderId);
                paymentMap.put("paymentId", paymentId);
                paymentMap.put("paymentName", paymentName);
                paymentMap.put("paymentTime", paymentTime);
                paymentMap.put("virtualGoods",virtualGoods);
                paymentMap.put("orderIsShopTake",orderIsShopTake);
                ResponseResult isUpdateOrderBase = orderServiceClient.UpdateOrderBaseByPayment(paymentMap);
                boolean is = new Boolean(String.valueOf(isUpdateOrderBase.getData())).booleanValue();
                if (is) {
                    LOGGER.info("-----UpdateOrderBaseByPaymentSuccess-----");
                } else {
                    LOGGER.info("-----UpdateOrderBaseByPaymentFail-----");
                }
            } else {
                LOGGER.info("-----UpdateTrade&RecordStatusFail-----");
            }
            LOGGER.info("EndUpdateTrade&RecordStatusTheFirstTime:" + DateUtils.getNowDateToDf());
        } catch (Exception e) {
            LOGGER.info("changeStatusErrorResults:" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            // 发送feign请求，更改payment状态
            Map<String, Object> paymentMap = new HashMap<String, Object>();
            Integer paymentId = 1;// 支付方式
            // 支付方式名称
            String paymentName = "在线支付";
            if (type==12) {
                paymentId = 2;
                paymentName = "线下支付";
            }
            // 分辨余额与购物卡
            paymentMap.put("type", type);
            paymentMap.put("payOrderId", orderId);
            paymentMap.put("paymentId", paymentId);
            paymentMap.put("paymentName", paymentName);
            paymentMap.put("paymentTime", paymentTime);
            paymentMap.put("virtualGoods",virtualGoods);
            paymentMap.put("orderIsShopTake",orderIsShopTake);
            orderServiceClient.UpdateOrderBaseByPayment(paymentMap);
        }
        return;
    }

    /**
     * 微信小程序支付回调判断该订单是否是 虚拟 / 自提 订单 如果是 生成兑换码
     * @param orderIdIsNum
     */
    public Map<String,Integer> virtualWxExchangeCode(Map<String,String> orderIdIsNum){
        Integer virtualGoods =null;
        String  orderId = null;
        String redeemCodeUrl =null;
        String code= null;
        Integer orderIsShopTake = null;
        Map<String, Integer> judgeOrderMap = new HashMap<>();
        try {
            ResponseResult res = orderServiceClient.isVirtualOrder(orderIdIsNum);
            Map<String,Object> map = (Map<String,Object>)res.getData();
            virtualGoods = (Integer) map.get("virtualGoods");
            orderId = (String)map.get("orderId");
            orderIsShopTake = (Integer) map.get("orderIsShopTake");
            //虚拟订单 0 是 1 否
            if(null != virtualGoods &&  0 == virtualGoods || null != orderIsShopTake && 1 == orderIsShopTake){
                SimpleDateFormat df = new SimpleDateFormat("ddHHmmss");
                String timeStamp = df.format(new Date());
                String temp = String.valueOf(Math.round((Math.random()+1) * 1000));
                code = temp+timeStamp;

                ResponseResult responseResult = QrCodeUtil.GenerateQRCode(code);
                redeemCodeUrl = String.valueOf(thirdPartyServiceClient.uploadToOssBase64((OssUploadUpdateParamDTO) responseResult.getData()).getData());
                Map<String,Object> param = new HashMap<>();
                param.put("order",orderId);
                param.put("redeemCode",code);
                param.put("redeemCodeUrl",redeemCodeUrl);
                //为虚拟拟订单添加兑换码
                orderServiceClient.addRedeemCode(param);
            }

            judgeOrderMap.put("virtualGoods",virtualGoods);
            judgeOrderMap.put("orderIsShopTake",orderIsShopTake);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return judgeOrderMap;
    }
}
